package icu.yougan.trade.utils;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import icu.yougan.trade.service.OrderService;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
@Log4j2
public class AliPay {
    @Autowired
    private OrderService orderService;
    //appid
    private final String APP_ID = "9021000143684376";
    //应用私钥
    @Value("${ali.alipayPrivateKey}")
    private String APP_PRIVATE_KEY;
    @Value("${ali.charset}")
    private String CHARSET;
    // 支付宝公钥
    @Value("${ali.alipayPublicKey}")
    private String ALIPAY_PUBLIC_KEY;
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    @Value("${ali.gateway-url}")
    private String GATEWAY_URL;
    @Value("${ali.format}")
    private String FORMAT;
    //签名方式
    @Value("${ali.signType}")
    private String SIGN_TYPE;
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    @Value("${ali.notify-url}")
    private String NOTIFY_URL;
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    @Value("${ali.return-url}")
    private String RETURN_URL;
    private AlipayClient alipayClient = null;

    @PostConstruct
    public void init() throws AlipayApiException {
        // 初始化时创建AlipayClient，避免每次调用都新建
        this.alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                APP_ID,
                APP_PRIVATE_KEY,
                FORMAT,
                CHARSET,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE
        );
    }
    //支付宝官方提供的接口
    public String sendRequestToAlipay(String outTradeNo, BigDecimal totalAmount, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("返回的结果是："+result );
        return result;
    }

    //    通过订单编号查询
    public String query(String id){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
    public String sendRefundRequest(
            String outTradeNo,
            String outRequestNo,
            BigDecimal refundAmount,
            String refundReason
    ) throws AlipayApiException {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        // 使用FastJSON构建JSON
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("refund_amount", refundAmount); // 确保金额格式正确
        bizContent.put("out_request_no", outRequestNo);
        bizContent.put("refund_reason", refundReason);

        request.setBizContent(bizContent.toString());

        // 添加日志
        log.info("支付宝退款请求参数: {}", bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);

        // 添加日志
        log.info("支付宝退款响应: {}", response.getBody());

        return response.getBody();
    }
}
